package com.lam.schedule.common.scheduler.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lam.common.exception.BaseException;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.SpringUtils;
import com.lam.common.utils.StringUtils;
import com.lam.schedule.common.scheduler.annotation.TaskTarget;
import com.lam.schedule.entity.ScheduleJob;

/**
 * @author lam
 *
 */
public class InvokeUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(InvokeUtils.class);
	
	private InvokeUtils() {
		throw new IllegalStateException("Utility class");
	}
	
//	public static void invokeJob(ScheduleJob scheduleJob) {
//		invokeJob(scheduleJob, null);
//	}
	
	public static void invokeJob(ScheduleJob scheduleJob, Map<String, Object> param) {
		
		Map<String, Object> exeParam = new HashMap<>();
		try {
			Map<String, Object> jobExeParam = JsonUtil.parseJSON(scheduleJob.getExeParam());
			if(CollectionUtil.isNotEmpty(jobExeParam)){
				exeParam.putAll(jobExeParam);
			}
			if(CollectionUtil.isNotEmpty(param)){
				exeParam.putAll(param);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException("定时任务启动失败, 参数解析错误!", e);
		}
			
		invoke(scheduleJob, exeParam);
	}
	
	/**
	 * 通过反射调用scheduleJob中定义的方法
	 * 
	 * @param scheduleJob
	 * @param exeParam 
	 */
	private static void invoke(ScheduleJob scheduleJob, Map<String, Object> exeParam) {
		Object bean = null;
		if (StringUtils.isNotBlank(scheduleJob.getExeClass())) {
			bean = getTargetObjectByType(scheduleJob);
		}else{
			logger.error("定时任务未配置执行目标对象, job:{}", scheduleJob);
			throw new BaseException("未配置执行目标对象");
		}
		if (bean == null) {
			logger.error("定时任务配置的执行目标对象为空，请检查配置, job:{}", scheduleJob);
			throw new BaseException("定时任务配置的执行目标对象为空");
		}
		Method method = null;
		try {
			method = bean.getClass().getMethod(scheduleJob.getExeMethod(), Map.class);
		} catch (NoSuchMethodException e) {
			logger.error("任务启动失败，执行方法不存在, job:{}", scheduleJob);
			throw new BaseException("定时任务启动失败, 执行方法不存在!", e);
		} catch (SecurityException e) {
			logger.error("任务启动失败，执行方法不可访问, job:{}", scheduleJob);
			throw new BaseException("定时任务启动失败, 执行方法不可访问!", e);
		} catch (Exception e) {
			logger.error("任务启动失败，方法错误, job:{}", scheduleJob);
			throw new BaseException("定时任务启动失败, 方法设置错误!", e);
		}
		
		try {
			method.invoke(bean, exeParam);
		} catch (Exception e) {
			if(e instanceof InvocationTargetException) {
				Throwable be = ((InvocationTargetException) e).getTargetException();
				if(be instanceof BaseException) {
					logger.error("定时任务执行失败, error:{}, job:{}", be.getMessage(), scheduleJob);
					throw (BaseException)be;
				}
			}
			logger.error("定时任务执行异常, job:"+scheduleJob, e);
			throw new BaseException("定时任务执行失败, 方法调用异常!", e);
		}
	}

	private static Object getTargetObjectByType(ScheduleJob scheduleJob){
		
		try {
			Class<?> clazz = Class.forName(scheduleJob.getExeClass());
			Object object = SpringUtils.getBean(clazz);
			if(object == null){
				object = clazz.getDeclaredConstructor().newInstance();
			}
			return object;
		} catch (ClassNotFoundException e) {
			logger.error("调度任务执行找不到执行目标类, job:"+scheduleJob, e);
			throw new BaseException("找不到执行目标类", e);
		} catch (InstantiationException | IllegalAccessException e) {
			logger.error("调度任务执行执行目标类实例化失败, job:"+scheduleJob, e);
			throw new BaseException("执行目标类实例化失败", e);
		} catch (Exception e) {
			logger.error("调度任务执行定时任务配置执行目标对象类型异常, job:"+scheduleJob, e);
			throw new BaseException("定时任务启动失败", e);
		}
	}
	
	/**
	 * 检查job的有效性
	 * @param job
	 * @return
	 * @date 2017年5月23日
	 * @author lam
	 */
	public static String checkJob(ScheduleJob job) {
		if(StringUtils.isBlank(job.getJobName())){
			return "任务名称不能为空";
		}
		String msg = CronUtils.valid(job.getCronExpression());
		if(com.lam.common.utils.StringUtils.isNotBlank(msg)) {
			return msg;
		}
		
		if(StringUtils.isBlank(job.getExeClass())){
			return "执行目标类ExeClass不能为空";
		}
		if(StringUtils.isBlank(job.getExeMethod())){
			return "执行方法不能为空";
		}
		
		Class<?> clazz = null;
		try {
			clazz = Class.forName(job.getExeClass());
			if(clazz.getAnnotation(TaskTarget.class) == null){
				return "目标类不可用于定时调度";
			}
		} catch (ClassNotFoundException e) {
			logger.error("无效的类路径", e);
			return "无效的类路径";
		} 
		
		try {
			SpringUtils.getBean(clazz);
		} catch (Exception e) {
			logger.error("不存在的执行类实例", e);
			return "执行类实例无法正常调用";
		}
		
		try {
			Method method = clazz.getMethod(job.getExeMethod(), Map.class);
			if(method.getAnnotation(TaskTarget.class) == null){
				return "目标方法不可用于定时调度";
			}
		} catch (NoSuchMethodException e) {
			return "执行方法不存在或无效, 方法参数类型必须为Map<String, Object>";
		} catch (SecurityException e) {
			return "执行方法不可访问";
		}
		
		if(StringUtils.isNotBlank(job.getExeParam())){
			try {
				JsonUtil.parseJSON(job.getExeParam());
			} catch (Exception e) {
				return "参数请填写json格式";
			}
		}
		
		return null;
	}
}